package org.ht.controller;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.ht.pojo.Biao;
import org.ht.pojo.Certification;
import org.ht.pojo.Details;
import org.ht.pojo.InvestInfo;
import org.ht.pojo.Product;
import org.ht.pojo.Trade;
import org.ht.pojo.Users;
import org.ht.service.BiaoService;
import org.ht.service.BidService;
import org.ht.service.CertificationService;
import org.ht.service.DetailsService;
import org.ht.service.InvestService;
import org.ht.service.ProductService;
import org.ht.service.TradeService;
import org.ht.util.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
@RequestMapping("/invest")
public class InvestController {
	@Autowired
	private InvestService investService;
	
	// private BorrowmoneyService service;
	@Autowired
	private ProductService productService;

	@Autowired
	private DetailsService detailsService;

	@Autowired
	private BiaoService biaoService;

	@Autowired
	private CertificationService certificationService;
	
	@Autowired
	private TradeService tradeService;
	
	@Autowired
	private BidService bidService;
	
	
	HttpSession session = null;
	ServletContext application = null;
	
	@RequestMapping("investSel")
	public String investSel(HttpServletRequest req, Model model, String item,
			String param, String currpage) {
		int pagerow = 5;// 每页5行
		int currpages = 1;// 当前页
		int totalpage = 0;// 总页数
		int totalrow = 0;// 总行数

		int outcount = 0;// 不够一页的数据条数
		int count = 0;//

		if (item != null && !item.equals("")) {//!lastUrl.equals(nowUrl)  && bl
			Map<String, Object> map = new HashMap<String, Object>();
			if (session == null) {
				session = req.getSession();
			}
			if (item.equals("itemtype")) {// 项目类型
				if (param.equals("-1")) {// 不限
					if (session.getAttribute("biaoId") != null) {
						System.out.println("进来了");
						session.removeAttribute("biaoId");
					}
				} else{
					session.setAttribute("biaoId", param);
				}
			}
			if (item.equals("rate")) {// 利率
				if (param.equals("-1")) {// 不限
					if (session.getAttribute("pincome") != null) {
						session.setAttribute("startR", "-1");
						session.removeAttribute("pincome");
					}
				}
				if (param.equals("1")) {// 12%以下
					session.setAttribute("startR", "0");
					session.setAttribute("endR", "12");
					session.setAttribute("pincome", "");
				}
				if (param.equals("2")) {// 12%-15%
					session.setAttribute("startR", "12");
					session.setAttribute("endR", "15");
					session.setAttribute("pincome", "");
				}
				if (param.equals("3")) {// 15%-20%
					session.setAttribute("startR", "15");
					session.setAttribute("endR", "20");
					session.setAttribute("pincome", "");
				}
				if (param.equals("4")) {// 20%及以上
					session.setAttribute("startR", "20");
					session.setAttribute("pincome", "");
					session.setAttribute("endR", "");
				}
			}
			if (item.equals("timelimit")) {// 期限 此处默认一个月为30天
				if (param.equals("-1")) {// 不限
					if (session.getAttribute("pcount") != null) {
						session.setAttribute("startT", "-1");
						session.removeAttribute("pcount");
					}
				}
				if (param.equals("1")) {// 1月以下
					session.setAttribute("startT", "0");
					session.setAttribute("endT", "30");
					session.setAttribute("pcount", "");
				}
				if (param.equals("2")) {// 1-3月
					session.setAttribute("startT", "30");
					session.setAttribute("endT", "90");
					session.setAttribute("pcount", "");
				}
				if (param.equals("3")) {// 3-6月
					session.setAttribute("startT", "90");
					session.setAttribute("endT", "180");
					session.setAttribute("pcount", "");
				}
				if (param.equals("4")) {// 6-12月
					session.setAttribute("startT", "180");
					session.setAttribute("endT", "360");
					session.setAttribute("pcount", "");
				}
				if (param.equals("5")) {// 12月及以上
					session.setAttribute("startT", "360");
					session.setAttribute("endT", "");
					session.setAttribute("pcount", "");
				}
			}
			if (item.equals("repayway")) {// 还款方式
				if (param.equals("-1")) {// 不限
					session.setAttribute("pway", "");
				}
				if (param.equals("1")) {
					session.setAttribute("pway", "到期还本付息");
				}
				if (param.equals("2")) {
					session.setAttribute("pway", "按月付息,到期还本");
				}
				if (param.equals("3")) {
					session.setAttribute("pway", "等额本息");
				}

			}
			// +hs.getAttribute("endR")==null"": +hs.getAttribute("endT")
			System.out.println("session中的标主键 " + session.getAttribute("biaoId") + ""
					+ "session中的利率开始点  " + session.getAttribute("startR")
					+ "session中的期限开始点" + session.getAttribute("startT")
					+ "session中的还款方式" + session.getAttribute("way"));
			System.out.println("map中的标主键 " + map.get("biaoId") + "利率开始点 "
					+ map.get("startR") + "期限开始点 " + map.get("startT")
					+ "还款方式 " + map.get("way"));
			if (session != null) {
				map.put("pincome", session.getAttribute("pincome"));
				map.put("pcount", session.getAttribute("pcount"));

				map.put("biaoId", session.getAttribute("biaoId"));
				map.put("startR", session.getAttribute("startR"));
				map.put("endR", session.getAttribute("endR"));
				map.put("startT", session.getAttribute("startT"));
				map.put("endT", session.getAttribute("endT"));
				map.put("pway", session.getAttribute("pway"));
			}
			System.out.println("map中的标主键 " + map.get("biaoId") + "利率开始点 "
					+ map.get("startR") + "期限开始点 " + map.get("startT")
					+ "还款方式 " + map.get("pway"));

			List<Product> page = productService.selList(map);

			totalrow = page.size();// 获取总行数
			if (currpage != null && !"".equals(currpage)) {
				currpages = Integer.parseInt(currpage);
			}
			// totalpage = (totalrow + pagerow - 1) / pagerow;

			outcount = totalrow % pagerow;
			count = totalrow / pagerow;

			totalpage = count;

			if (outcount > 0) {
				totalpage = count + 1;
			}

			if (currpages < 1) {
				currpages = 1;
			}
			if (currpages > totalpage) {
				currpages = totalpage;
			}

			if (currpages == 0) {
				currpages = 1;
			}

			Integer candp = (currpages - 1) * pagerow;
			map.put("startPage", candp);
			map.put("pageSize", 5);

			List<Product> pages = productService.selList(map);
			model.addAttribute("totalrow", totalrow);
			model.addAttribute("currpages", currpages);
			model.addAttribute("totalpage", totalpage);
			model.addAttribute("list", pages);

		} else {

			Product pro = new Product();
			@SuppressWarnings("unchecked")
			List<Product> page = productService.findList(BeanUtils.toMap(pro));

			totalrow = page.size();// 获取总行数
			if (currpage != null && !"".equals(currpage)) {
				currpages = Integer.parseInt(currpage);
			}
			// totalpage = (totalrow + pagerow - 1) / pagerow;

			outcount = totalrow % pagerow;
			count = totalrow / pagerow;

			totalpage = count;

			if (outcount > 0) {
				totalpage = count + 1;
			}

			if (currpages < 1) {
				currpages = 1;
			}
			if (currpages > totalpage) {
				currpages = totalpage;
			}

			if (currpages == 0) {
				currpages = 1;
			}

			Integer candp = (currpages - 1) * pagerow;
			pro.setStartPage(candp);
			pro.setPageSize(5);

			@SuppressWarnings("unchecked")
			List<Product> list = productService.findList(BeanUtils.toMap(pro));
			model.addAttribute("totalrow", totalrow);
			model.addAttribute("currpages", currpages);
			model.addAttribute("totalpage", totalpage);
			model.addAttribute("list", list);
		}

		Map<String, Object> map = new HashMap<String, Object>();
		List<Biao> biao = biaoService.findList(map);
		model.addAttribute("biao", biao);

		return "list";
	}

	@RequestMapping("recommendShow")
	public String recommendShow(HttpServletRequest req,Model model) {// 首页中显示推荐
		Map<String, Object> parameters = new HashMap<String, Object>();// 查询条件
		 
		// parameters.put("pandc", 2);
		// parameters.put("candp", 1);
		// parameters.put("bstate", "招标中");
		// parameters.put("brecommend", "推荐");
//		bidService.chuli();
//		bidService.chuli2();
		 if(application == null){
				List<Product> proList = new ArrayList<Product>();

//				parameters.put("pageSize",5);
//				parameters.put("startPage",0);
//				List<Product> tmpP=productService.selList(parameters);

				List<Biao> list = biaoService.findList(parameters);//查找标的数量
				if (list != null && list.size() > 0) {
					parameters.put("pageSize", 3);
					parameters.put("startPage", 0);
					for (int i = 0; i < list.size(); i++) {
						Biao biao = list.get(i);
						parameters.put("biaoId", biao.getId());
						List<Product> tlist = productService.selList(parameters);// 两条数据
						for (int j = 0; j < tlist.size(); j++) {
							proList.add(tlist.get(j));// 将所有标的内容都加到里面，统一显示在前端
						}
					}
				}
					
//				parameters.remove("biaoId");
//				parameters.put("pcount", "");//推荐  还款日期 - 项目期限 < 一个月的
//				parameters.put("startT", "0");
//				parameters.put("endT", "30");
//				List<Product> tjl = productService.selList(parameters);
				
//				model.addAttribute("proList", proList);
//				model.addAttribute("biaoList", list);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("rowName", "inmoney");// 查出投资总额
				map.put("tableName", "investinfo");
				
				Double tm = investService.sumMoney(map);  //投资总额
				
				application = req.getSession().getServletContext();
				application.setAttribute("proList", proList);
				application.setAttribute("biaoList", list);
//				application.setAttribute("tjlist", tjl);
				application.setAttribute("ztz", tm);
		 }
		
		// List<Borrowmoney> list = service.pagingSel(parameters);
		// model.addAttribute("list", list);

		return "index";
	}

	@RequestMapping("investInfo")
	public String investInfo(
			String bmid,String currpage,
			Model model, HttpServletRequest req) {// Borrowmoney bm
		System.out.println(bmid.toString());

		int pagerow = 5;// 每页5行
		int currpages = 1;// 当前页
		int totalpage = 0;// 总页数
		int totalrow = 0;// 总行数

		int outcount = 0;// 不够一页的数据条数
		int count = 0;//

		Map<String, Object> parameters = new HashMap<String, Object>();// 查询条件
		parameters.put("bid", bmid);
    	List<InvestInfo> page = investService.investS(parameters);// 查出数据条数
		totalrow = page.size();// 获取总行数
		System.out.println("此标的投资信息记录条数"+totalrow);
		if (currpage != null && !"".equals(currpage)) {
			currpages = Integer.parseInt(currpage);
		}

		outcount = totalrow % pagerow;
		count = totalrow / pagerow;

		totalpage = count;

		if (outcount > 0) {
			totalpage = count + 1;
		}

		if (currpages < 1) {
			currpages = 1;
		}
		if (currpages > totalpage) {
			currpages = totalpage;
		}

		Integer candp = (currpages - 1) * pagerow;
		if(candp < 0){
			candp = 0;
		}
		parameters.put("pandc", 5);    //总条数
		parameters.put("candp", candp);//起始点
		
		List<InvestInfo> lists = investService.investS(parameters);

		model.addAttribute("totalrow", totalrow);
		model.addAttribute("currpages", currpages);
		model.addAttribute("totalpage", totalpage);
		model.addAttribute("bmid", bmid);
		model.addAttribute("record", lists);

		// 查出一些总额
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rowName", "inmoney");// 查出投资总额
		map.put("tableName", "investinfo");
		map.put("bid", bmid);//获得此标的所有投资记录
		
		Double tm = investService.sumMoney(map);   //此标总投了多少钱
		model.addAttribute("tm", tm);
		System.out.println("tm" + tm);
		map.put("rowName", "profitmoney");// 查出收益总额

		Double gm = investService.sumMoney(map);      //收益总额
		model.addAttribute("gm", gm);
		System.out.println("gm" + gm);

		Map<String, Object> bmap = new HashMap<String, Object>();
		List<Biao> biao = biaoService.findList(bmap);
		model.addAttribute("biao", biao);

		
		
		Product pro = productService.get(Integer.parseInt(bmid));  //select * from product where id = ? 
		HttpSession bms = req.getSession();
		bms.setAttribute("Borrowmoney", pro);
		
		//待还本息
		double principalInteres = pro.getPtotalmoney() * (1 + Double.parseDouble(pro.getPincome()) / 100.0);
		DecimalFormat df = new DecimalFormat("#.00");
		model.addAttribute("principalInteres", df.format(principalInteres));
		
		List<Details> list = detailsService.detailslist(pro.getId());  //select * from Details where pid=? 
		System.out.println("标详情列表大小" + list.size());
		bms.setAttribute("Product", pro);
		bms.setAttribute("Details", list);

		System.out.println("pro.getPstate()获取到的值为   " + pro.getPstate());
		long days = (pro.getPcount().getTime() - pro.getPtime().getTime())
				/ (24 * 60 * 60 * 1000);
		bms.setAttribute("days", days);
		if (pro.getPstate().equals("1")) {
			Users us = (Users) req.getSession().getAttribute("globaluser");
			if(us != null){
				String kymoney = certificationService.selectM(us.getUid());
				System.out.println("进入到输入金额页面  用户余额"+kymoney);
				bms.setAttribute("kymoney", kymoney);
			}
			return "inforadd";
		} else {
			System.out.println("进入到显示页面");
			return "infor";
		}
	}

	@RequestMapping("investAdd")
	public String investAdd(
			@RequestParam(value = "money", required = false) String money,
			HttpServletRequest req,Model model) {// 投标
										// @RequestParam(value="",requested=false)
										// InvestInfo ii
		HttpSession httpSession = req.getSession();
		// Borrowmoney bm = (Borrowmoney) hs.getAttribute("Borrowmoney");
		// System.out.println(bm.getBlimit());

		Product product = (Product) httpSession.getAttribute("Product");

		InvestInfo investInfo = new InvestInfo();
		Users user = (Users) httpSession.getAttribute("globaluser");
		// inid; //'投资信息表主键',
		// ii.setInid(2);
		if(user != null){
			investInfo.setUserid(user.getUid()); // '投资用户主键',
			// ii.setBrrowid(bm.getId()); //'投标的主键',
			investInfo.setBrrowid(product.getId());//
			investInfo.setInmoney(new BigDecimal(money)); // '投资金额',
			investInfo.setInstatus("不用"); // '投资状态 0 收益中的投资 1已完成的投资',
			investInfo.setInstyle("不用"); // '投资类型',
			// brrowstatus;// '借贷状态是否凑资完',
			investInfo.setBrrowstatus("不用");
			investInfo.setInterest(product.getPincome()); // '投资利率',
			investInfo.setProfitmodel(product.getPway()); // '盈利方式 如等额本金',
		
			investInfo.setProfitmoney(new BigDecimal((1 + Double.parseDouble(product.getPincome()) / 100.0) * Double.parseDouble(money))); // '盈利金额',
			
			Date date = new Date();
			// @SuppressWarnings("deprecation")
			// String d = date.toLocaleString();
			@SuppressWarnings("deprecation")
			Timestamp timestamp = new Timestamp(date.getYear(), date.getMonth(),
					date.getDay(), date.getHours(), date.getMinutes(),
					date.getSeconds(), 0);
			investInfo.setIndate(timestamp); // '投资时间，可为空'

			// ii.setReplaydate(Integer.parseInt(bm.getBlimit())); //
			long days = (product.getPcount().getTime() - product.getPtime().getTime())
					/ (24 * 60 * 60 * 1000);// 相差几天
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String ds = sdf.format(product.getPcount());  //还款时间

			investInfo.setReplaydate(ds + "(共" + days + "天)");
			investInfo.setMarkstatus(0); // '投标状态 0默认投标中 1 投标通过（中标） 2投标未通过（失标）';

			System.out.println(investInfo.toString());
			httpSession.removeAttribute("Product");
			httpSession.removeAttribute("Details");
			investService.investA(investInfo);//添加投资记录

			//从用户可用余额中扣除金额
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("uid", user.getUid());
			String kym = (String) req.getSession().getAttribute("kymoney");//可用总金额
			double nkym = Double.parseDouble(kym) - Double.parseDouble(money);//扣除投资后剩余的可用金额
			Certification certification = certificationService.select(user.getUid());
			certification.setCbalance(nkym);
			//增加待收本息
			certification.setCdue(certification.getCdue() + Double.parseDouble(money) + 
								 (double)days / 365 * Double.parseDouble(money) * Double.parseDouble(product.getPincome()) / 100.0 );  
			certificationService.update(certification);
			//			map.put("money",nkym);
//			certificationService.updateM(map);
			httpSession.removeAttribute("kymoney");
			//写入用户账户金额记录表
			Trade td = new Trade();
			td.setuID(user.getUid());
			td.setUname(user.getUnickname());
			td.setZname(user.getUname());
			td.setJymoney(money);
			td.setOther("要投资就要舍得花钱");
			td.setWhat("投资");
			tradeService.addDate(td);
			//修改项目凑集资金
//			Product product = proS.get(pro.getId());
			Double updMoney = Double.parseDouble(product.getPmoney()+"") + Double.parseDouble(money);
			System.out.println("修改完后的金额"+updMoney);
			product.setPmoney(updMoney.intValue());
			product.setProgress(String.valueOf(product.getPmoney() / product.getPtotalmoney() * 1.0));
			productService.update(product);
			//判断项目是否满标
			DecimalFormat df = new DecimalFormat( "0.00");
			String udm = df.format(updMoney).toString();
			String odm = df.format(product.getPtotalmoney()).toString();
			if (updMoney >= product.getPtotalmoney()) {
				product.setPstate("2");//修改为凑资完
				productService.update(product);
			}
//			if(udm.equals(odm)){//刚好凑集完
//				product.setPstate("2");//修改为凑资完
//				productService.update(product);
//			}
			httpSession.setAttribute("end", "end");
		}
		
		return "redirect:investInfo.do?bmid="+product.getId();
	}

	@RequestMapping("investRecord")
	public String investRecord(Model model,
			@RequestParam(value = "currpage", required = false) String currpage,HttpServletRequest req) {// 查出投资记录
		Users u = (Users) req.getSession().getAttribute("globaluser");
		
		int pagerow = 5;// 每页5行
		int currpages = 1;// 当前页
		int totalpage = 0;// 总页数
		int totalrow = 0;// 总行数

		int outcount = 0;// 不够一页的数据条数
		int count = 0;//

		Map<String, Object> parameters = new HashMap<String, Object>();// 查询条件
		if(u != null){//用户已登录就查出此用户的数据否则所有数据
			parameters.put("uid", u.getUid());
		}
		List<InvestInfo> page = investService.investS(parameters);// 查出数据条数
		totalrow = page.size();// 获取总行数
		System.out.println("此标的投资信息记录条数"+totalrow);
		if (currpage != null && !"".equals(currpage)) {
			currpages = Integer.parseInt(currpage);
		}
		// totalpage = (totalrow + pagerow - 1) / pagerow;

		outcount = totalrow % pagerow;
		count = totalrow / pagerow;

		totalpage = count;

		if (outcount > 0) {
			totalpage = count + 1;
		}

		if (currpages < 1) {
			currpages = 1;
		}
		if (currpages > totalpage) {
			currpages = totalpage;
		}
		// Integer pandc = pagerow * currpages;
		Integer candp = (currpages - 1) * pagerow;
		if(candp < 0){
			candp = 0;
		}
		parameters.put("pandc", 5);
		parameters.put("candp", candp);
		List<InvestInfo> list = investService.investS(parameters);

		model.addAttribute("totalrow", totalrow);
		model.addAttribute("currpages", currpages);
		model.addAttribute("totalpage", totalpage);
		model.addAttribute("record", list);

		// 查出一些总额
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rowName", "inmoney");// 查出投资总额
		map.put("tableName", "investinfo");
		if(u != null){//用户已登录就查出此用户的数据否则所有数据
			map.put("uid", u.getUid());
		}
		Certification c = certificationService.select(u.getUid());
		Double tm = investService.sumMoney(map);//查出投资总额
		model.addAttribute("tm", tm);
		System.out.println("tm" + tm);

		map.put("rowName", "profitmoney");
		Double gm = investService.sumMoney(map);// 查出收益总额
		model.addAttribute("gm", gm);
		System.out.println("gm" + gm);

		//查出退还的本金
		List<Trade> tmonery = tradeService.selectMoney(u.getUid());
		Integer allM = 0;
		for(Trade tr : tmonery){
			String money = tr.getJymoney().replace("+", "");
			allM += Integer.parseInt(money);
		}
		System.out.println("退还本金总额"+allM);
		
		model.addAttribute("dsbx", c.getCdue());
		//查出总收益
		Integer gtm = investService.getMoney(u.getUid());
		model.addAttribute("gtm", gtm);
		
		Map<String, Object> bmap = new HashMap<String, Object>();
		List<Biao> biao = biaoService.findList(bmap);
		model.addAttribute("biao", biao);
		model.addAttribute("thm", allM);
		return "investrecord";
	}

	public static void main(String s[]) {
		Date date = new Date();
		long dl = date.getTime();// 将日期转换成毫秒数
		System.out.println(dl + "");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date d = new Date();
		try {
			d = sdf.parse("2017-03-05 20:27:00");
		} catch (ParseException e) {
			e.printStackTrace();
		}
		long dt = d.getTime();
		long day = (dt - dl) / (24 * 60 * 60 * 1000);
		System.out.println(day + "天");
	}
}
